package com.mio.scalademo


import akka.actor.{Actor, ActorRef, ActorSystem, Props}

import scala.io.StdIn


class AActor(actorRef: ActorRef) extends Actor {
  var i:Int = 0;
  val bActorRef: ActorRef = actorRef
  // 接收消息并处理
  override def receive: Receive = {
    
    case "拜拜" => {
      //关闭自己
      context.stop(self)
      //关闭ActorSystem
      context.system.terminate()
    }
    case "start" =>{
       println("AActor 出招了")
       println("start, ok!")
       println("我打")
       self ! "我打" 
    }
    case "我打" => {
      i = i+1
      println("AActor(黄飞鸿)： 厉害！佛山无影脚第"+i+"脚")
      Thread.sleep(1000)
      bActorRef ! "我打" //给 BActor 发出消息
    }
  }
}

class BActor extends Actor {
  var i:Int = 0;
  // 接收消息并处理
  override def receive: Receive = {
    
    case "拜拜" => {
      //关闭自己
      context.stop(self)
      //关闭ActorSystem
      context.system.terminate()
    }
    case "我打"  =>{
      i = i+1
      println("BActor(乔峰)：挺猛，看我降龙十八掌...第"+i+"掌")
      Thread.sleep(1000)
      //通过 sender() 可以获取到发现消息的 actor 的 ref
      sender() ! "我打"
    } 
  }
}

object DaActor {
  
   def main(args: Array[String]): Unit = {
      val MyFactory = ActorSystem("myFactory")

      // 通过MyFactory.actorOf方法来创建一个actor；
       val bActorRef = MyFactory.actorOf(Props[BActor], "bActor")
       val aActorRef: ActorRef = MyFactory.actorOf(Props(new AActor(bActorRef)), "aActor")
       aActorRef ! "start"
       
      
  }
}